import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ClientHandler implements Runnable {
    private Socket clientSocket;
    private boolean isReconnected;
    private static ConcurrentLinkedQueue<Socket> clientSockets = new ConcurrentLinkedQueue<>();
    private byte[] buffer = new byte[2048]; // 缓冲区大小调整为 2048
    private int bufferIndex = 0; // 记录缓冲区当前索引

    public ClientHandler(Socket clientSocket, boolean isReconnected) {
        this.clientSocket = clientSocket;
        this.isReconnected = isReconnected;
        if (!isReconnected) {
            clientSockets.add(clientSocket);
        }
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = clientSocket.getInputStream();
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer, bufferIndex, buffer.length - bufferIndex))!= -1) {
                bufferIndex += bytesRead;
                if (bufferIndex >= buffer.length) {
                    // 缓冲区已满，进行数据转发
                    for (Socket otherSocket : clientSockets) {
                        if (otherSocket!= clientSocket && otherSocket.isConnected()) {
                            try {
                                OutputStream outputStream = otherSocket.getOutputStream();
                                outputStream.write(buffer, 0, buffer.length);
                            } catch (IOException e) {
                                clientSockets.remove(otherSocket);
                            }
                        }
                    }
                    bufferIndex = 0; // 重置缓冲区索引
                }
            }
            // 如果还有剩余数据未发送，进行发送
            if (bufferIndex > 0) {
                for (Socket otherSocket : clientSockets) {
                    if (otherSocket!= clientSocket && otherSocket.isConnected()) {
                        try {
                            OutputStream outputStream = otherSocket.getOutputStream();
                            outputStream.write(buffer, 0, bufferIndex);
                        } catch (IOException e) {
                            clientSockets.remove(otherSocket);
                        }
                    }
                }
            }
        } catch (IOException e) {
            handleDisconnect(e);
        }
    }

    private void handleDisconnect(IOException e) {
        if (e.getMessage().contains("Connection reset by peer")) {
            clientSockets.remove(clientSocket);
            System.out.println("客户端 " + clientSocket.getInetAddress() + " 异常断开连接");
        } else {
            e.printStackTrace();
        }
    }
}